<template>
  <div class="warpper-box businessOrder">
    <enterprise-select v-if="userInfo.type == 4" ref="enterprise" @enterpriseChange="enterpriseChange"></enterprise-select>
    <a-card style="margin-top: 10px;">
      <a-form layout="inline">
        <a-form-item label="月份选择">
          <a-month-picker valueFormat="YYYY-MM" placeholder="选择月份" v-model="params.insureDate"></a-month-picker>
        </a-form-item>
        <a-form-item label="结算状态">
          <a-select v-model="params.orderStatus" placeholder="选择结算状态" style="width: 160px;">
            <a-select-option key="1">待提交</a-select-option>
            <a-select-option key="2">待支付</a-select-option>
            <a-select-option key="3">已支付</a-select-option>
            <a-select-option key="4">已拒绝</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" icon="search" @click="loadTable(true)">搜索</a-button>
          <a-button type="primary" icon="setting" @click="reset()">重置</a-button>
          <a-button type="primary" @click="addOrder">生成商保订单</a-button>
          <a-button type="primary" @click="downloadOrder">导出</a-button>
        </a-form-item>
      </a-form>
      <a-table :columns="table.columns" :data-source="table.loadData" :pagination="table.pagination"
        @change="handleTableChange" rowKey="insureNo" style="margin-top: 10px;">
        <!-- 操作栏-->
        <span slot="action" slot-scope="text, record">
          <!-- 编辑模块 | 字段 -->
          <span v-if="record.orderStatus == 1">
            <a-popconfirm title="确认提交?" ok-text="确认" cancel-text="取消" @confirm="operate(record, 2)">
              <a>提交</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a-popconfirm title="确认撤销?" ok-text="确认" cancel-text="取消" @confirm="operate(record, 1)">
              <a>撤销</a>
            </a-popconfirm>
            <a-divider type="vertical" />
          </span>
          <span v-else-if="record.orderStatus == 2">
            <a-popconfirm title="确认支付?" ok-text="确认" cancel-text="取消" @confirm="operate(record, 3)">
              <a>支付</a>
            </a-popconfirm>
            <a-divider type="vertical" />
            <a-popconfirm title="确认拒绝?" ok-text="确认" cancel-text="取消" @confirm="operate(record, 4)">
              <a>拒绝</a>
            </a-popconfirm>
            <a-divider type="vertical" />
          </span>
          <a @click="$refs.createInfo.add(record.insureNo,record.orderStatus)">详情</a>
          <a-divider type="vertical" />
          <a @click="downloadDetail(record)">导出详情</a>
        </span>
      </a-table>
    </a-card>
    <add-info ref="createInfo" @on-ok="addLoad"></add-info>

    <!-- 生成商保订单 -->
    <a-modal v-model="createVisible" title="生成商保订单" width="700px" @ok="addFormSubmit">
      <a-space style="padding-left: 80px;">
        <span style="color: rgba(0, 0, 0, 0.85);">参保月份：</span>
        <a-month-picker placeholder="请选择月份" valueFormat="YYYY-MM" v-model="insureDate" style="width: 320px;"></a-month-picker>
      </a-space>
      <a-space style="padding-left: 52px;padding-top: 10px;">
        <span style="color: rgba(0, 0, 0, 0.85);">商保订单名称：</span>
        <a-input placeholder="请输入方案名称" v-model="insureName" style="width: 320px;"/>
      </a-space>
      <a-space style="padding-left: 66px;padding-top: 10px;margin-bottom: 20px;">
        <span style="color: rgba(0, 0, 0, 0.85);">服务商选择：</span>
        <a-select placeholder="请选择订单服务商" v-model="parkId" style="width: 320px;">
          <a-select-option v-for="item in parkList" :key="item.parkId">{{ item.parkName }}</a-select-option>
        </a-select>
      </a-space>
      <a-space style="padding-left: 80px;margin-bottom: 20px;">
        <span style="color: rgba(0, 0, 0, 0.85);">合作类型：</span>
        <a-select @change="bizTypeChange" placeholder="请选择合作类型" v-model="bizId" style="width: 320px;">
          <a-select-option v-for="item in bizTypeList" :key="item.bizId" :bizTypeName="item.bizTypeName">{{ item.bizTypeName }}</a-select-option>
        </a-select>
      </a-space>
      <a-alert message="填写导入数据信息：请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除" type="info" />
      <a-button type="primary" @click="downloadCreate" ghost
        style="display: block;margin: 20px auto;width: 160px;">下载模板</a-button>
      <a-alert message="上传填好的信息表：文件后缀名必须为xls 或xlsx （即Excel格式），文件大小不得大于10M，最多支持导入3000条数据" type="info" />
      <div v-if="fileName" style="width: 260px;display: flex;justify-content: space-between;align-items: center;margin: 20px auto;">
        <span style="flex-shrink: 0;">{{ fileName }}</span>
        <a-icon type="delete" @click="delFile" style="color: #ff4d4f;" />
      </div>
      <div v-else>
        <a-button type="primary" @click="importCreate" :disabled="!insureDate || !insureName || !parkId"
          style="display: block;margin: 20px auto;width: 160px;">上传文件</a-button>
        <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileExcel"
          @change="importCreateHandle" style="display: none;" />
      </div>
    </a-modal>
  </div>
</template>

<script>
import store from '@/store'
import EnterpriseSelect from "@/components/human/enterpriseSelect.vue"
import {
  COLUMNS_BUSINESSORDER
} from "./form"
import AddInfo from "./businessOrder_add.vue"
import {
  getTablePage,
  downloadInsureBusinessExcelTemplate,
  businessAdd,
  businessOperate,
  exportInsureBusiness,
  exportInsureBusinessStaff
} from "@/api/human/ensureBusinessOrder"
import {
  parkRelation,
  listEnterpriseBizType
} from "@/api/human/ensurePayOrder"
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'businessOrder',
  components: {
    AddInfo,
    EnterpriseSelect
  },
  data() {
    return {
      params: {
        orderStatus: undefined,
        insureDate: '',
      },
      table: {
        columns: COLUMNS_BUSINESSORDER,
        loadData: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      pagination: { current: 1, pageSize: 10 },

      createVisible: false,
      insureName: "", // 商保订单名称
      insureDate: "", // 参保月份
      parkId: undefined, // 服务商
      bizTypeName: "",
      fileName: "",
      formData: undefined, // 生成保单参数

      enterpriseId: "", // 企业id
      enterpriseData: [], // 客户列表
      parkList: [], // 服务商列表
      bizId: undefined,
      bizTypeList: [], // 业务类型列表

      selectedRowKeys: [], // 选择的table数据id
      selectedRows: [], // 选择的table数据
    }
  },
  filters: {

  },
  mounted() {
    window.addEventListener('keyup', this.keyDown);
    if (this.userInfo.type == 4) {
      this.$refs.enterprise.getEnterpriseData();
    } else {
      this.enterpriseId = this.userInfo.relationId;
      this.loadTable(true);
    }
  },
  destroyed() {
    window.removeEventListener('keyup', this.keyDown);
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    })
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {

  },
  methods: {
    // table复选框选择
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 获取列表
    async loadTable(flag) {
      let params = this.params;
      if (flag) {
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.enterpriseId = this.enterpriseId;
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const { code, data } = await getTablePage(params);
      if (code === '1') {
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination) {
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    // 类型选择
    bizTypeChange(value, option) {
      this.bizTypeName = option.data.attrs.bizTypeName
    },
    // 导出订单
    downloadOrder() {
      exportInsureBusiness({ 
        enterpriseId: this.enterpriseId, 
        orderStatus: this.params.orderStatus,
        insureDate: this.params.insureDate
      }).then(res => {
        const blob = new Blob([res]);
        const fileName = '商保管理订单.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 导出详情
    downloadDetail(row) {
      exportInsureBusinessStaff({
        insureNo: row.insureNo
      }).then(res => {
        const blob = new Blob([res]);
        const fileName = '商保管理订单详情.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 支付|拒绝|提交|撤销
    async operate(row, type) {
      let params = {
        insureNo: row.insureNo,
        operateType: type
      }
      const { code } = await businessOperate(params)
      if (code == 1) {
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    // 获取业务类型列表
    async getListEnterpriseBizType() {
      const { code, data } = await listEnterpriseBizType(this.enterpriseId);
      if (code == "1") {
        this.bizTypeList = data;
      }
    },
    // 生成商保订单
    addOrder() {
      this.createVisible = true;
      this.insureDate = "";
      this.insureName = "";
      this.parkId = undefined;
      this.bizId = undefined;
      this.bizTypeName = "";
      this.delFile();
      this.getParkRelation();
      this.getListEnterpriseBizType();
    },
    // 删除上传文件
    delFile() {
      this.fileName = "";
      this.formData = undefined;
    },
    // 下载模板
    downloadCreate() {
      downloadInsureBusinessExcelTemplate().then(res => {
        const blob = new Blob([res]);
        const fileName = '商保人员模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 导入表单
    importCreate() {
      this.$refs.fileExcel.click();
    },
    importCreateHandle(e) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) {
        return;
      }
      if (file.name.indexOf('.xls') === -1) {
        _this.$message.error("只支持xlsx");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 20)) {
        _this.$message.error('模版大小不能超过 20MB!');
        e.target.value = "";
        return;
      }
      e.target.value = "";
      if (file) {
        let formData = new FormData();
        formData.append("enterpriseId", _this.enterpriseId);
        formData.append("insureName", _this.insureName);
        formData.append("insureDate", _this.insureDate);
        formData.append("parkId", _this.parkId);
        formData.append("bizId", _this.bizId);
        formData.append("file", file);
        this.formData = formData;
        this.fileName = file.name;
      }
    },
    // 提交
    async addFormSubmit() {
      if (!this.insureDate) {
        return this.$message.warning('请选择月份');
      }
      if (!this.insureName) {
        return this.$message.warning('请输入商保订单名称');
      }
      if (!this.parkId) {
        return this.$message.warning('请选择服务商');
      }
      if (!this.bizId) {
        return this.$message.warning('请选择合作类型');
      }
      if (!this.formData) {
        return this.$message.warning('请上传文件');
      }
      this.submitLoading = true;
      const { code } = await businessAdd(this.formData);
      this.submitLoading = false;
      if (code === '1') {
        this.createVisible = false;
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    // 企业选择回调
    enterpriseChange(value) {
      this.enterpriseId = value;
      this.loadTable(true);
    },
    // 获取服务商列表
    async getParkRelation() {
      this.events_form.resetFields("parkId");
      const { code, data } = await parkRelation(this.enterpriseId);
      if (code == "1") {
        this.parkList = data;
      }
    },
    addLoad() {
      this.loadTable(true);
    },
    reset() {
      this.params.insureDate = '';
      this.params.orderStatus = undefined;
      this.loadTable(true);
    }
  }
}
</script>
<style lang="less">
.businessOrder {
  .ant-tabs-bar {
    margin-bottom: 5px;
  }
}
</style>